const msg = (title, icon = 'none', duration = 1500, mask = true) => {
	uni.showToast({
		title: title,
		icon: icon,
		duration: duration,
		mask
	})
}

const error = (title) => {
	uni.showToast({
		title: title,
		icon: title.length <= 7 ? 'error' : 'none',
		duration: 2000,
		mask: true
	})
}

const success = (title) => {
	uni.showToast({
		title: title,
		icon: title.length <= 7 ? 'success' : 'none',
		duration: 1500,
		mask: false
	})
}

const formatDateTime = (date, dateSeparator = '-', timeSeparator = ':') => {
	const year = date.getFullYear()
	const month = date.getMonth() + 1
	const day = date.getDate()
	const hour = date.getHours()
	const minute = date.getMinutes()
	const second = date.getSeconds()

	return [year, month, day].map(formatNumber).join(dateSeparator) + ' ' + [hour, minute, second].map(formatNumber)
		.join(timeSeparator)
}

const formatDate = (date, separator = '') => {
	const year = date.getFullYear()
	const month = date.getMonth() + 1
	const day = date.getDate()

	return [year, month, day].map(formatNumber).join(separator);
}

const formatNumber = n => {
	n = n.toString()
	return n[1] ? n : '0' + n
}

const timeout = (ms) => {
	return new Promise(resolve => setTimeout(resolve, ms));
}

const getTime = (time) => {
	return new Date(time.replace(/-/g, '/')).getTime();
}

const compare = (prop) => {
	return function(obj1, obj2) {
		let val1 = obj1[prop];
		let val2 = obj2[prop];
		if (val1 > val2) {
			return 1;
		} else if (val1 < val2) {
			return -1;
		} else {
			return 0;
		}
	}
}

const reverseCompare = (prop) => {
	return function(obj1, obj2) {
		let val1 = obj1[prop];
		let val2 = obj2[prop];
		if (val1 < val2) {
			return 1;
		} else if (val1 > val2) {
			return -1;
		} else {
			return 0;
		}
	}
}

const getSuffix = (res) => {
	let index = res.lastIndexOf(".");
	let suffix = res.substring(index + 1);
	return suffix;
}

/**参数说明： 
 * 
 * 根据长度截取先使用字符串，超长部分追加…
 * @param {String} str 对象字符串 
 * @param {Integer} len 目标字节长度,字母数字算1,表情算2，中文算2
 * 返回值： 处理结果字符串 
 */
const cutStrWithEllipsis = (str, len) => {
	let strlen = 0;
	let tempArr = [];
	let tempStr = '';
	let i = 0;
	let _iteratorNormalCompletion = true;
	let _didIteratorError = false;
	let _iteratorError = undefined;
	try {
		for (var _iterator = str[Symbol.iterator](), _step; !(_iteratorNormalCompletion = (_step = _iterator.next())
				.done); _iteratorNormalCompletion = true) {
			let v = _step.value;
			tempArr[i] = v;
			tempStr = tempStr + v;
			i = i + 1;
			if (tempStr != str) {
				//还没有到最后
				if (v.charCodeAt(0) > 128) {
					strlen = strlen + 2;
					if (strlen >= len) {
						return tempArr.slice(0, tempArr.length - 1).join('') + "..."; //...也占用len里面的位置
					}
				} else {
					strlen = strlen + 1;
					if (strlen >= len) {
						return tempArr.slice(0, tempArr.length - 2).join('') + "..."; //...也占用len里面的位置
					}
				}
			}
		}
	} catch (err) {
		_didIteratorError = true;
		_iteratorError = err;
	} finally {
		try {
			if (!_iteratorNormalCompletion && _iterator.return) {
				_iterator.return();
			}
		} finally {
			if (_didIteratorError) {
				throw _iteratorError;
			}
		}
	}
	return tempStr;
}

const chooseImage = async (count = 1) => {
	return new Promise(async (resolve, reject) => {
		try {
			let {
				tapIndex
			} = await uni.showActionSheet({
				alertText: '请选择图片来源',
				itemList: ["手机拍照", "从相册选取", "从微信选择"],
				itemColor: "#599bff"
			});
			let tempFiles;
			if (tapIndex == 2) {
				let res = await uni.chooseMessageFile({
					count,
					type: 'all',
				})
				tempFiles = res.tempFiles.filter(i => {
					return i.type === "image";
				})
			} else {
				let res = await uni.chooseMedia({
					count,
					mediaType: ["image"],
					sourceType: [tapIndex == 0 ? "camera" : "album"],
					sizeType: ["original", "compressed"],
					camera: "back",
				})
				tempFiles = res.tempFiles.filter(i => {
					return i.fileType === "image";
				})
			}
			let list = tempFiles.map(i => {
				let path = i.path || i.tempFilePath;
				return {
					path,
					name: UUID(3) + Date.now() + "_S" + i.size + "_." + getSuffix(path),
					size: i.size
				};
			})
			resolve(list);
		} catch (e) {
			reject(e);
		}
	})
}

/**
 * 生成UUID
 * 
 * @param {长度} len
 * @param {分割符} delimiter
 */
const UUID = (len = 32, delimiter) => {
	let radix = 16; //16进制
	let chars = '0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz'.split('');
	let uuid = [],
		i;
	radix = radix || chars.length;
	if (delimiter) {
		let r;
		uuid[8] = uuid[13] = uuid[18] = uuid[23] = delimiter;
		uuid[14] = '4';
		for (i = 0; i < len + 4; i++) {
			if (!uuid[i]) {
				r = 0 | Math.random() * 16;
				uuid[i] = chars[(i == 19) ? (r & 0x3) | 0x8 : r];
			}
		}
	} else {
		for (i = 0; i < len; i++) {
			uuid[i] = chars[0 | Math.random() * radix];
		}
	}
	return uuid.join('');
}

const imgLoad = (image) => {
	return new Promise(function(resolve, reject) {
		image.onload = () => {
			resolve(image);
		}
		image.onerror = (err) => {
			console.log(err)
			reject(err)
		}
	})
}

const goBack = () => {
	if (getCurrentPages().length == 1) {
		uni.switchTab({
			url: "/pages/index/index"
		})
	} else {
		uni.navigateBack({
			delta: 1
		})
	}
}

const getDateType = (targetDateStr) => {
	let targetDate = new Date(targetDateStr.replace(/-/g, '/'));
	let today = new Date();
	let yesterday = new Date(new Date().setDate(today.getDate() - 1));
	let theDayBeforeYesterday = new Date(new Date().setDate(today.getDate() - 2));
	if (targetDate.getDate() === today.getDate()) {
		return '今天';
	} else if (targetDate.getDate() === yesterday.getDate()) {
		return '昨天';
	} else if (targetDate.getDate() === theDayBeforeYesterday.getDate()) {
		return '前天';
	}
	return targetDateStr.substr(5, 5);
}

const parseAddress = (res) => {
	let regex = /^(北京市|天津市|重庆市|上海市|香港特别行政区|澳门特别行政区)/;
	let REGION_PROVINCE = [];
	let addressBean = {
		REGION_PROVINCE: null,
		REGION_COUNTRY: null,
		REGION_CITY: null,
		ADDRESS: null
	};

	function regexAddressBean(address, addressBean) {
		let regex = /^(.*?[市州]|.*?地区|.*?特别行政区)(.*?[市区县])(.*?)$/g;
		let addxress = regex.exec(address);
		addressBean.REGION_CITY = addxress[1];
		addressBean.REGION_COUNTRY = addxress[2];
		addressBean.ADDRESS = addxress[3] + "(" + res.name + ")";
		console.log(addxress);
	}
	if (!(REGION_PROVINCE = regex.exec(res.address))) {
		regex = /^(.*?(省|自治区))(.*?)$/;
		REGION_PROVINCE = regex.exec(res.address);
		addressBean.REGION_PROVINCE = REGION_PROVINCE[1];
		regexAddressBean(REGION_PROVINCE[3], addressBean);
	} else {
		addressBean.REGION_PROVINCE = REGION_PROVINCE[1];
		regexAddressBean(res.address, addressBean);
	}
	return addressBean;
}

/**
 * 封装微信的获取定位功能
 */
const getLocation = () => {
	return new Promise(function(resolve, reject) {
		uni.getLocation({
			// type: 'wgs84',
			type: 'gcj02', //更准确
			// #ifdef MP-WEIXIN
			isHighAccuracy: true, //开启精确定位
			// #endif
			highAccuracyExpireTime: 10000, //精确定位超时时间
			success(res) {
				resolve(res);
			},
			fail(res) {
				reject(res);
			}
		})
	});
}

/**
 * 计算两经纬度之间的直线距离
 */
const getDistance = (lat1, lng1, lat2, lng2) => {
	var radLat1 = lat1 * Math.PI / 180.0;
	var radLat2 = lat2 * Math.PI / 180.0;
	var a = radLat1 - radLat2;
	var b = (lng1 * Math.PI / 180.0) - (lng2 * Math.PI / 180.0);
	var s = 2 * Math.asin(Math.sqrt(Math.pow(Math.sin(a / 2), 2) +
		Math.cos(radLat1) * Math.cos(radLat2) * Math.pow(Math.sin(b / 2), 2)));
	s = s * 6378.137; // EARTH_RADIUS;
	// s = Math.round(s * 1000);
	s = s.toFixed(2);
	return s;
}

/**
 * 校验手机号码格式
 */
const validatePhoneNumberStrict = (phone) => {
	const regex = /^1[3-9]\d{9}$/; // 以 1 开头，第二位是 3-9，后面跟 9 位数字
	return regex.test(phone);
}


// 1. 姓名脱敏处理
const desensitizeName = (name) => {
	if (!name || typeof name !== 'string') return '';

	const length = name.length;

	if (length <= 1) {
		return name;
	} else if (length === 2) {
		// 两个字：将最后一个字变成*
		return name.charAt(0) + '*';
	} else {
		// 三个字及以上：保留第一个和最后一个，中间全部变成*
		const firstChar = name.charAt(0);
		const lastChar = name.charAt(length - 1);
		const middleStars = '*'.repeat(length - 2);
		return firstChar + middleStars + lastChar;
	}
}

// 2. 身份证号码脱敏处理
const desensitizeIdCard = (idCard) => {
	if (!idCard || typeof idCard !== 'string') return '';

	const length = idCard.length;

	if (length <= 6) {
		return idCard; // 长度不足6位，不做处理
	} else {
		// 保留前3位和后3位，中间全部变成*
		const firstThree = idCard.substring(0, 3);
		const lastThree = idCard.substring(length - 3);
		const middleStars = '*'.repeat(length - 6);
		return firstThree + middleStars + lastThree;
	}
}

export default {
	msg, //默认消息提示框
	error, //错误消息提示框，字符大于7时无图标
	success, //成功消息提示框，字符大于7时无图标
	formatDateTime, //日期时间格式化，默认格式为【yyyy-MM-dd HH:mm:ss】，可设置分隔符
	formatDate, //日期格式化，默认格式为【yyyyMMhh】,可设置分隔符
	getTime, //根据字符串的时间格式获取时间戳
	timeout, //同步的时间阻塞
	compare, //升序
	reverseCompare, //降序
	getSuffix, //获取文件后缀
	cutStrWithEllipsis, //根据长度截取先使用字符串，超长部分追加…
	chooseImage, //选择图片
	UUID, //获取随机数
	imgLoad, //canvas下载图片
	goBack, //返回上一页或首页
	getDateType, //获取是今天、昨天、前天或日期
	parseAddress, //返回省市区
	getLocation, //获取定位
	getDistance, //计算距离
	validatePhoneNumberStrict, //校验手机号码格式
	desensitizeName,
	desensitizeIdCard,
}